import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import {getUserInfo} from "src/utils/auth";
import setting from 'src/settings'
import store from 'src/store'
import {getToken} from 'src/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: '/', // url = base url + request url
  baseURL: process.env.VUE_APP_BASE_API + setting.apiVersion, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
      config.data.acode = getUserInfo() ? JSON.parse(getUserInfo()).uid : '';
      config.data.token = getToken() ? getToken() : '';
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    res => {
      if (res.data.code !== 200) {
        Message({
          message: res.data.msg || 'Error',
          type: 'error',
        });
        if (res.data.code === 100 || res.data.code === 20000 || res.data.code === 20002) {
          // to re-login
          MessageBox.alert(res.data.msg, '请重新登录', {
            confirmButtonText: '确定',
            showClose: false,
            type: 'warning',
            center: true,
            callback: () => {
              store.dispatch('user/resetToken').then(() => {
                location.reload()
              })
            }
          })
        }
        return Promise.reject(res.data)
      } else {
        return res.data
      }
    },
    error => {
      Message({
        message: error.message,
        type: 'error',
      });
      return Promise.reject(error)
    }
)

export default service
